package cn.itsource.pethome.basic.controller;

import cn.itsource.pethome.basic.util.AjaxResult;
import cn.itsource.pethome.basic.util.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.jni.Multicast;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @description: 描述:
 * @date: 2020/8/11 18:35
 * @author: summer
 * version: 1.0
 */
@RestController
@RequestMapping("/common")
public class FastDftController {

    @PostMapping("/fastDfs")
    public AjaxResult update(@RequestPart(required = true,value = "file")MultipartFile file) throws IOException {
        try {
            //获取附件名
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String extension = FilenameUtils.getExtension(fileName);
            //上传  返回上传路径
            String upload = FastDfsApiOpr.upload(file.getBytes(), extension);
            return new AjaxResult().setResult(upload);
        }  catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "上传失败");
        }
    }

    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String,String> partm){
        try {
            String url = partm.get("url");
            String path = url.substring(1);
            String groupName = url.substring(0, path.indexOf("/"));
            String fileName = path.substring(path.indexOf("/")+1);
            FastDfsApiOpr.delete(groupName,fileName );
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
}
